<?php
Zend_Session::start();
/**
 *  @copyright 2011
 *  @package _version@
 *  @author oriotiori
 */

class Admin_LoginController extends Zend_Controller_Action
{

	public function init(){
	}

	public function indexAction()
	{

		//$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout->disableLayout();
		$s_Sass = new Zend_Session_Namespace('s_Sass');


		if($this->_request->isPost()){

			$data=$this->_request->getPost();

			$authAdapter = $this->getAuthAdapter();
			$username = (!empty($data['username'])) ? $data['username'] : '0000';
			$password = $data['password'];

			$authAdapter->setIdentity($username)->setCredential(md5($password));

			$auth = Zend_Auth::getInstance();
			$result = $auth->authenticate($authAdapter);

			if($result->isValid()){
				$identity = $authAdapter ->getResultRowObject();
				$authStorage = $auth ->getStorage();
				$authStorage->write($identity);

				if(isset($s_Sass->redirectafterloginorregister) && !empty($s_Sass->redirectafterloginorregister)){
					$this->_redirect($s_Sass->redirectafterloginorregister);
				}
				else {
					$this->_redirect('admin'. DIAG_PATH .'index');
				}

			} else{
				$s_Sass->ErrorMessage= "<strong>Autentificacion fallada:</strong> combinaci&oacute;n usuario-contrase&ntilde;a incorrecta";
				$this->_redirect('admin'. DIAG_PATH .'login');
			}
		}
		 


		if(Zend_Auth::getInstance()->hasIdentity()){
			if($s_Sass->Role=="1")
				$this->_redirect('admin'. DIAG_PATH );
			else
				$this->_redirect('index'. DIAG_PATH );

		}


		if(strlen($s_Sass->ErrorMessage) > 0){
			$this->view->errorMessage= $s_Sass->ErrorMessage;
			$s_Sass->ErrorMessage='';
		}
	}



	public function logoutAction()
	{
		$s_Sass = new Zend_Session_Namespace('s_Sass');
		$s_Sass->unsetAll();
		Zend_Auth::getInstance()->clearIdentity();
		$this->_redirect('index');
	}

	public function noaccessAction()
	{
		$this->_helper->layout->disableLayout();
		$s_Sass = new Zend_Session_Namespace('s_Sass');
		
	}

	public function getAuthAdapter()
	{
		$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
		$authAdapter 	->setTableName(TABLE_PREFIX.'users')
			->setIdentityColumn('Username')
			->setCredentialColumn('Password');

		return $authAdapter;
	}


}



